package com.zzyl.nursing.service.impl;

import java.lang.invoke.VarHandle;
import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.util.IDCardUtils;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-20
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 获取入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        //老人相关的
        //通过id找到入住配置   拿到老人id
        CheckIn checkIn = checkInMapper.selectCheckInById(id);

        Elder elder = elderMapper.selectById(checkIn.getElderId());
        if(ObjectUtil.isNotEmpty(elder)){
            CheckInElderVo checkInElderVo = new CheckInElderVo();
            BeanUtils.copyProperties(elder,checkInElderVo);
            //补全年龄属性,通过身份证号来计算老人的年龄，工具类可以使用AI协助创建
            checkInElderVo.setAge(IDCardUtils.getAgeByIdCard(elder.getIdCardNo()));
            vo.setCheckInElderVo(checkInElderVo);
        }


        //入住配置
        LambdaQueryWrapper<CheckInConfig> checkInConfigWrapper = new LambdaQueryWrapper<>();
        checkInConfigWrapper.eq(CheckInConfig::getCheckInId,checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigWrapper);
        //属性拷贝，BeanUtil.toBean：拷贝数据并创建对象（糊涂工具提供）
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);

        /*CheckInConfigVo  cif = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,cif);*/

        //补全其他属性
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        vo.setCheckInConfigVo(checkInConfigVo);

        //合同
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId,elder.getId());
        Contract contract = contractMapper.selectOne(contractWrapper);
        vo.setContract(contract);

        //家属列表
        String otherApplyInfo = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(otherApplyInfo, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVos);

        return vo;
    }

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    /**
     * 申请入住
     *
     * @param dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {

        try {
            //校验老人是否已入住
            LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
            elderQueryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
            elderQueryWrapper.eq(Elder::getStatus, 1);
            Elder elder = elderMapper.selectOne(elderQueryWrapper);
            if (ObjectUtils.isNotEmpty(elder)) {
                throw new BaseException("该老人已入住" );
            }

            //更新床位的状态
            Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
            bed.setBedStatus(1);
            bedMapper.updateById(bed);

            //新增或更新老人elder
            elder = insertOrUpdateElder(dto.getCheckInElderDto(), bed);

            //新增合同信息
            String contractNo = "HT" + CodeGenerator.generateContractNumber();
            insertContract(contractNo, elder, dto);

            //新增入住信息
            CheckIn checkIn = insertCheckIn(dto,elder);

            //新增入住配置
            insertCheckInConfig(dto, checkIn);
        } catch (BaseException e) {
            throw new RuntimeException(e);
        }

    }

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 新增入住配置
     * @param dto
     * @param checkIn
     */
    private void insertCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param dto
     * @param elder
     * @return
     */
    private CheckIn insertCheckIn(CheckInApplyDto dto, Elder elder) {
        CheckIn checkIn = new CheckIn();

        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        //保存老人的家属列表
        String json = JSON.toJSONString(dto.getElderFamilyDtoList());
        checkIn.setRemark(json);
        System.out.println(json);
        List<ElderFamilyDto> elderFamilyDtos = JSON.parseArray(json, ElderFamilyDto.class);
        System.out.println(elderFamilyDtos);
        //保存
        save(checkIn);
        return checkIn;
    }

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 新增合同信息
     *
     * @param contractNo
     * @param elder
     * @param dto
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto dto) {

        //属性拷贝
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        //设置状态  使用当前时间来做判断
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0; //代表左边的时间在当前时间之前，则表示已经生效
        contract.setStatus(status);
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     *
     * @param checkInElderDto
     * @param bed
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {

        //属性拷贝
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //查询老人是否存在
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        elderQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        elderQueryWrapper.eq(Elder::getStatus, 0);
        Elder elderDb = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            elder.setId(elderDb.getId());
            //更新
            elderMapper.updateById(elder);
        } else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }
}
